package com.lcc.book.demos.web.Service;

import com.lcc.book.demos.web.Mapper.BookInfoMapper;
import com.lcc.book.demos.web.Model.BookInfo;
import com.lcc.book.demos.web.Model.PageResult;
import com.lcc.book.demos.web.Model.PageRequest;
import com.lcc.book.demos.web.enums.BookStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Service
public class BookService {
    @Autowired
    private BookInfoMapper bookInfoMapper;
    public PageResult<BookInfo> selectBookInfoByPage(PageRequest pageRequest){
        //获取总记录数
        Integer count = bookInfoMapper.count();
        //调用Mapper里面的方法，获取当前页面的记录
        List<BookInfo> bookList = bookInfoMapper.selectBookInfoByPage(pageRequest.getOffset(),pageRequest.getPageSize());
        if(bookList != null || bookList.size() > 0){
            //根据状态码返回图书状态
            for(BookInfo bookInfo:bookList){
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getName());
//                if(bookInfo.getStatus() == 1){
//                    bookInfo.setStatusCN("可借阅");
//                }else if(bookInfo.getStatus() == 2){
//                    bookInfo.setStatusCN("不可借阅");
//                }
            }
        }
        return new PageResult<>(count,bookList,pageRequest);
    }

    public Integer addBook(BookInfo bookInfo){
        Integer result = 0;
        try {
            result = bookInfoMapper.addBookInfo(bookInfo);
        }catch (Exception e){
            log.error("添加图书出错，e:{}" + e);
        }
        return result;
    }

    /**
     * 通过id来获取图书
     * @param bookId
     * @return
     */
    public BookInfo selectBookInfoById(Integer bookId){
        BookInfo bookInfo = null;
        //调用Mapper
        try {
            bookInfo = bookInfoMapper.selectBookInfoById(bookId);
        }catch (Exception e){
            log.error("查询图书出错，e:{}" + e);
        }
        return bookInfo;
    }

    /**
     * 更新图书
     * @param bookInfo
     * @return
     */
    public Integer updateBookInfo(BookInfo bookInfo){
        //调用Mapper
        Integer result = 0;
        try {
            result = bookInfoMapper.updateBookInfo(bookInfo);
        }catch (Exception e){
            log.error("更新图书失败，e:{}",e);
        }
        return result;
    }

    /**
     * 批量删除图书
     * @param ids
     * @return
     */
    public Integer batchDelete(@RequestParam List<Integer> ids){
        Integer result =0;
        try {
            //调用MyBatis
            result = bookInfoMapper.batchDelete(ids);
        }catch (Exception e){
            e.printStackTrace();
            log.error("批量删除图书失败, ids:{}",ids);
        }
        return result;
    }
}
